package com.kotodama.interfaces.web.auth;

import com.kotodama.application.services.UserService;
import com.kotodama.domain.entities.User;
import com.kotodama.infrastructure.security.JwtTokenProvider;
import com.kotodama.infrastructure.tenant.context.TenantContext;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jakarta.validation.Valid;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    private final AuthenticationManager authenticationManager;
    private final JwtTokenProvider tokenProvider;
    private final UserService userService;

    public AuthController(
            AuthenticationManager authenticationManager,
            JwtTokenProvider tokenProvider,
            UserService userService) {
        this.authenticationManager = authenticationManager;
        this.tokenProvider = tokenProvider;
        this.userService = userService;
    }

    @PostMapping("/login")
    public ResponseEntity<JwtAuthResponse> login(@Valid @RequestBody LoginRequest loginRequest) {
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        loginRequest.getUsername(),
                        loginRequest.getPassword()
                )
        );

        SecurityContextHolder.getContext().setAuthentication(authentication);
        String tenantId = TenantContext.getTenantId();
        Object principal = authentication.getPrincipal();
        org.springframework.security.core.userdetails.UserDetails userDetails;
        if (principal instanceof org.springframework.security.core.userdetails.UserDetails) {
            userDetails = (org.springframework.security.core.userdetails.UserDetails) principal;
        } else {
            // 根据实际情况，这里可能需要抛出异常或记录错误，因为我们期望的是 UserDetails
            // 为了编译通过，暂时假设如果不是 UserDetails，则无法生成 token 或抛出运行时异常
            // 在实际应用中，需要更健壮的错误处理
            throw new IllegalStateException("Authentication principal is not an instance of UserDetails: " + principal.getClass().getName());
        }
        String jwt = tokenProvider.generateToken(userDetails, tenantId);
        
        return ResponseEntity.ok(new JwtAuthResponse(jwt));
    }

    @PostMapping("/register")
    public ResponseEntity<String> register(@Valid @RequestBody RegisterRequest registerRequest) {
        if (userService.existsByUsername(registerRequest.getUsername())) {
            return ResponseEntity.badRequest().body("用户名已存在");
        }

        User user = new User();
        user.setUsername(registerRequest.getUsername());
        user.setPassword(registerRequest.getPassword()); // 将在 service 层加密
        user.setEmail(registerRequest.getEmail());
        user.setTenantId(TenantContext.getTenantId());

        userService.register(user);
        
        return ResponseEntity.ok("注册成功");
    }
}
